import axios from 'axios'
import storage from 'good-storage'
import { notify } from '@/quasar.js'
// console.log(notify)

const baseURL = 'http://server.weiwei8848.com'
const timeout = 7000
const intance = axios.create({
  baseURL,
  timeout  // 超时时间
})

intance.interceptors.request.use(config => {
  config.headers = getHeader()
  return config
}, error => {
  return Promise.error(error)
})
intance.interceptors.response.use((response) => {
  // console.log(response)
  if (response.status == 200) {
    return response.data
  }
  if (response.status != 200) {
    notify({
      type: 'negative',
      position: 'top-right',
      message: response.mes,
      timeout: 1000
    })
    return response.data
  }
}, error => {
  notify({
    type: 'negative',
    position: 'top-right',
    message: error.toString(),
    timeout: 2000
  })
  throw new Error(error)
})

class HTTP {
  async request({ url, data = {}, method = 'GET' }) {
    return intance({
      url,
      data,
      method,
    })
  }
}

function getHeader(headers = {}) {
  const token = storage.get('token')
  if (!token) {
    return headers
  }
  return Object.assign(headers, { token })
}

export default HTTP

